package com.example.antitouchscreen;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.content.Intent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.Manifest;
import java.text.ParseException;


public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button btnStart;
    private static final int REQUEST_CODE = 1;
    private static final int REQUEST_CODE_DRAW_OVERLAY = 101;
    private static final int REQUEST_CODE_POST_NOTIFICATIONS = 1;

    private static final String CHANNEL_ID = "anti_touch_channel";
    static final int NOTIFICATION_ID = 1;

    private EditText et_hours,et_minutes,et_seconds;
    private Switch st_show;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStart = findViewById(R.id.open);
        btnStart.setOnClickListener(this);
        et_hours=findViewById(R.id.hours);
        et_minutes=findViewById(R.id.minutes);
        et_seconds=findViewById(R.id.seconds);
        st_show=findViewById(R.id.switch1);
        Function_SharePreference sp=new Function_SharePreference(getApplicationContext());
        String show=sp.get("isShow");
        if(show.equals("false")){
            st_show.setChecked(true);

        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
            // 如果没有权限，则请求权限
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, REQUEST_CODE_DRAW_OVERLAY);
        } else {
            // 如果已经有权限，则继续执行悬浮窗相关操作
            // 例如：启动悬浮窗服务或显示悬浮窗
        }


        // 创建通知渠道
//        createNotificationChannel();

        // 请求POST_NOTIFICATIONS权限
//        requestPostNotificationsPermission();
        // 显示通知栏
//        showNotification();
//        open();




    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.channel_name);  // 渠道名称
            String description = getString(R.string.channel_description);  // 渠道描述
            int importance = NotificationManager.IMPORTANCE_DEFAULT;  // 渠道重要性
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);  // 设置渠道描述
            // 注册通知渠道，以便它不会在通知设置中被删除
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    private void showNotification() {
        long hours = Integer.parseInt(et_hours.getText().toString());
        long minutes = Integer.parseInt(et_minutes.getText().toString());
        long seconds=Integer.parseInt(et_seconds.getText().toString());
        long number=(hours * 60 + minutes) * 60 * 1000+seconds*1000;


        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
//        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("防触控制")
                .setContentText("点击按钮以启动功能")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setOngoing(true); // 设置为常驻通知

        // “防触”按钮
        Intent antiTouchIntent = new Intent(this, NotificationActionService.class);
        antiTouchIntent.setAction("ANTI_TOUCH");
//        PendingIntent antiTouchPendingIntent = PendingIntent.getService(this, 0, antiTouchIntent, PendingIntent.FLAG_UPDATE_CURRENT| PendingIntent.FLAG_IMMUTABLE);
//        NotificationCompat.Action antiTouchAction = new NotificationCompat.Action.Builder(R.drawable.ic_anti_touch, "防触", antiTouchPendingIntent).build();
//        builder.addAction(antiTouchAction);

        // “定时”按钮
        Intent timerIntent = new Intent(this, NotificationActionService.class);
        timerIntent.setAction("TIMER");
        // 将hours、minutes、seconds数据添加到Intent中，这里自定义了不同的键名用于区分不同数据
        timerIntent.putExtra("total_seconds", number);
//        PendingIntent timerPendingIntent = PendingIntent.getService(this, 0, timerIntent, PendingIntent.FLAG_UPDATE_CURRENT| PendingIntent.FLAG_IMMUTABLE);
//        NotificationCompat.Action timerAction = new NotificationCompat.Action.Builder(R.drawable.ic_timer, "定时", timerPendingIntent).build();
//        builder.addAction(timerAction);

        // “关闭”按钮
        Intent closeIntent = new Intent(this, NotificationActionService.class);
        closeIntent.setAction("CLOSE");

        PendingIntent antiTouchPendingIntent = PendingIntent.getService(this, 0, antiTouchIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        NotificationCompat.Action antiTouchAction = new NotificationCompat.Action.Builder(R.drawable.ic_anti_touch, "防触", antiTouchPendingIntent).build();
        builder.addAction(antiTouchAction);

        PendingIntent timerPendingIntent = PendingIntent.getService(this, 0, timerIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        NotificationCompat.Action timerAction = new NotificationCompat.Action.Builder(R.drawable.ic_timer, "定时", timerPendingIntent).build();
        builder.addAction(timerAction);

        PendingIntent closePendingIntent = PendingIntent.getService(this, 0, closeIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        NotificationCompat.Action closeAction = new NotificationCompat.Action.Builder(R.drawable.ic_close, "关闭", closePendingIntent).build();
        builder.addAction(closeAction);



        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(NOTIFICATION_ID, builder.build());
    }



    public void open(){
        // 启动透明悬浮页面的Activity
        Toast.makeText(getApplicationContext(), "已启动防触屏", Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(MainActivity.this, FloatingActivity.class);
//                startActivity(intent);
        moveTaskToBack(true);
// 启动悬浮窗服务
        startService(new Intent(this, FloatingService.class));

        // 将主页面隐藏到后台（只是将其置于后台，并非真正销毁，可根据业务需求调整）
//                moveTaskToBack(true);
    }
    public void openNotification(){

    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.open:
                Boolean show=st_show.isChecked();
                Function_SharePreference sp=new Function_SharePreference(getApplicationContext());
                if(show){
                    sp.set("isShow","false");

                }else{
                    sp.set("isShow","true");

                }
                // 创建通知渠道
        createNotificationChannel();

                // 请求POST_NOTIFICATIONS权限
        requestPostNotificationsPermission();
                showNotification();
                moveTaskToBack(true);
                break;



        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_DRAW_OVERLAY) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(this)) {
                    // 权限被授予，继续执行悬浮窗相关操作
                    // 例如：启动悬浮窗服务或显示悬浮窗
                } else {
                    // 权限被拒绝，向用户解释为什么需要这个权限
                    Toast.makeText(this, "需要悬浮窗权限以显示悬浮窗", Toast.LENGTH_SHORT).show();
                    // 可以选择关闭应用或引导用户手动开启权限
                }
            }
        }
    }



    private void requestPostNotificationsPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted, request it
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, REQUEST_CODE_POST_NOTIFICATIONS);
        } else {
            // Permission is already granted, you can show notifications
            showNotification();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_POST_NOTIFICATIONS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission was granted, you can show notifications
                showNotification();
            } else {
                // Permission was denied, you can't show notifications
                Toast.makeText(this, "通知权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }

}